import axios from "axios";
import Vue from "vue";
import store from "./store";
const CancelToken = axios.CancelToken;
const source = CancelToken.source();

const getHttp = () => {
  let http = axios.create({
    baseURL: process.env.VUE_APP_API_URL
      ? "http://localhost:8002/admin-api"
      : "/admin-api",
    timeout: 1000 * 60 * 10,
    cancelToken: source.token,
  });

  http.interceptors.request.use(
    function (config) {
      // Do something before request is sent
      if (store && store.state) {
        config.headers.Authorization = "Bearer " + store.state.user.accessToken;
      }
      return config;
    },
    function (error) {
      // Do something with request error
      if (axios.isCancel(error)) {
        console.log("Request canceled", error.message);
      }
      // return Promise.reject(error);
    }
  );
  http.interceptors.response.use(
    (res) => {
      return res;
    },
    (err) => {
      if (err.response.data && err.response.data.hasOwnProperty("message")) {
        Vue.prototype.$message({
          type: "error",
          message: err.response.data.message,
        });

        if (err.response.status === 401) {
          router.push("/login");
        }
      }
      return Promise.reject(err);
    }
  );

  http.cancel = () => {
    source.cancel();
    http = getHttp()
  };

  return http
}

let http = getHttp()

export default http;
